<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="部门id" prop="deptId" v-show="false">
        <el-input v-model="formData.deptId" placeholder="请输入部门id" />
      </el-form-item>
      <el-form-item label="产品编号" prop="productId">
        <el-input v-model="formData.productId" placeholder="请输入产品编号" />
      </el-form-item>

      <el-form-item label="产品名称" prop="productName">
        <el-select
          v-model="formData.productName"
          placeholder="请选择产品名称"
          @change="onChangeProduct"
        >
          <el-option
            v-for="item in productOptions"
            :key="item.name"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="产品名称" prop="productName">
        <el-input v-model="formData.productName" placeholder="请输入产品名称" />
      </el-form-item> -->
      <el-form-item label="产品单位" prop="productUnit">
        <el-input v-model="formData.productUnit" placeholder="请输入产品单位" />
      </el-form-item>
      <el-form-item label="产品规格" prop="productStandards">
        <el-input v-model="formData.productStandards" placeholder="请输入产品规格" />
      </el-form-item>
      <el-form-item label="产品单价" prop="productPrice">
        <el-input v-model="formData.productPrice" placeholder="请输入产品单价" />
      </el-form-item>

      <!-- <el-form-item label="库存数量" prop="count">
        <el-input v-model="formData.count" placeholder="请输入库存数量" />
      </el-form-item> -->
      <!-- <el-form-item label="申请数量" prop="quantity">
        <el-input v-model="formData.quantity" placeholder="请输入申请数量" />
    </el-form-item> -->

      <el-form-item label="申请数量" prop="quantity">
        <el-input-number
          v-model="formData.quantity"
          placeholder="请选择申请数量"
          :min="1"
          :step="1"
          type="number"
          controls-position="right"
          class="!w-100%"
        />
       
      </el-form-item>

      <el-form-item label="总价" prop="totalPrice">
        <!-- <el-input v-model="formData.totalPrice" placeholder="请输入总价" /> -->
        <el-input
              disabled
              v-model="formData.totalPrice"
              :formatter="erpPriceInputFormatter"
            />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.IS_STARTED)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { DepPlanApi, DepPlanVO } from '@/api/erp/depplan'
import { SecStockApi } from '@/api/erp/secstock'
import { StockApi } from '@/api/erp/stock/stock'
import {
  erpCountInputFormatter,
  erpPriceInputFormatter,
  erpPriceMultiply,
  getSumValue
} from '@/utils'

/** ERP 科室采购计划 表单 */
defineOptions({ name: 'DepPlanForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  deptId: undefined,
  productId: undefined,
  productName: undefined,
  productUnit: undefined,
  productStandards: undefined,
  productPrice: undefined,
  totalPrice: undefined,
  count: undefined,
  quantity: undefined,
  status: undefined,
  remark: undefined
})
const formRules = reactive({})
const formRef = ref() // 表单 Ref
const productOptions = ref([])

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DepPlanApi.getDepPlan(id)
    } finally {
      formLoading.value = false
    }
  }

  // 将deptId赋值给formData中的deptId
  formData.value.deptId = deptId
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as DepPlanVO
    if (formType.value === 'create') {
      await DepPlanApi.createDepPlan(data)
      message.success(t('common.createSuccess'))
    } else {
      await DepPlanApi.updateDepPlan(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

// 根据产品id改变产品信息
const onChangeProduct = (productName) => {
  // 根据产品id从产品选项中找到对应的产品
  const product = productOptions.value.find((item) => item.name === productName)


  if (product) {
    formData.value.productStandards = product.productStandards //产品规格
    formData.value.productUnit = product.productUnit //产品单位
    formData.value.productPrice = product.productPrice //产品单价

  }
  // setStockCount(product)
}

/** 加载库存 */
// const setStockCount = async (product) => {
//   if (!product.productId) {
//     return
//   }
//   const count = await StockApi.getStockCount(product.productId)
//   product.stockCount = count || 0
// }

    // 假设erpPriceMultiply是一个已经定义的函数，用于计算价格乘以数量
    const erpPriceMultiply = (productPrice, quantity) => {
      return productPrice * quantity;
    };

   // 使用watch来观察formData的变化
   watch(
      () => formData.value,
      (newVal) => {
        // console.log(newVal, 'newVal')
        // 注意：这里不会使用forEach，因为formData.value不是一个数组
        // 而是直接处理newVal（即formData.value的当前值）
        if (newVal.productName && newVal.productPrice && newVal.quantity) {
         
          // 计算总价和税价
          newVal.totalProductPrice = erpPriceMultiply(newVal.productPrice, newVal.quantity);
          newVal.taxPrice = erpPriceMultiply(newVal.totalProductPrice, newVal.taxPercent / 100.0);
          newVal.totalPrice = newVal.totalProductPrice + (newVal.taxPrice || 0);
        } else {
          // 如果必要属性不完整，则重置相关计算属性
          newVal.totalProductPrice = undefined;
          newVal.taxPrice = undefined;
          newVal.totalPrice = undefined;
        }
      },
      { deep: true } // 使用深度观察，以便在formData对象的属性发生变化时触发回调
    );



/** 合计 */
const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column, index: number) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (['quantity', 'productPrice'].includes(column.property)) {
      const sum = getSumValue(data.map((item) => Number(item[column.property])))
      sums[index] =
        column.property === 'quantity' ? erpCountInputFormatter(sum) : erpPriceInputFormatter(sum)
    } else {
      sums[index] = ''
    }
  }) 

  return sums
}

let deptId: number
onMounted(async () => {
  const Info = JSON.parse(localStorage.getItem('user') || '{}')
  const userInfo = JSON.parse(Info.v)
  deptId = userInfo.user.deptId

  productOptions.value = await SecStockApi.getSecStockListByDeptId(deptId)
  formData.value.deptId = deptId; 

})

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    deptId: undefined,
    productId: undefined,
    productName: undefined,
    productUnit: undefined,
    productStandards: undefined,
    productPrice: undefined,
    totalPrice: undefined,
    count: undefined,
    quantity: undefined,
    status: undefined,
    remark: undefined
  }
  formRef.value?.resetFields()
}
</script>